<?php

App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');

/**
 * Class User
 */
class User extends AppModel {

	public $useTable = 'Users';

	public $id = true;

	public $belongsTo = ['Role'];

	public $actsAs = ['Acl' => ['type' => 'requester']];

	public $validate = [
		'username' => [
			'rule' => 'notEmpty',
		],
		'password' => [
			'rule' => ['minLength', 6],
			'message' => 'Minimum 6 characters long',
		],
		'email' => [
			'rule' => 'notEmpty',
			'required' => 'create',
		],
	];

	/**
	 * parentNode method
	 *
	 * @return array|null
	 */
	public function parentNode() {
		if (!$this->id && empty($this->data)) {
			return null;
		}
		$roleId = Hash::get($this->data, 'User.role_id');
		if (empty($roleId)) {
			$roleId = $this->field('role_id');
		}
		if (!$roleId) {
			return null;
		}
		return array('Role' => array('id' => $roleId));
	}

	/**
	 * beforeSave method
	 *
	 * @param array $options
	 * @return bool
	 */
	public function beforeSave($options = []) {
		if (!parent::beforeSave($options)) {
			return false;
		}
//		$this->data[$this->alias]['id'] = String::uuid();
		if (isset($this->data[$this->alias]['password'])) {
			$hasher = new BlowfishPasswordHasher();
			$this->data[$this->alias]['password'] = $hasher->hash($this->data[$this->alias]['password']);
		}
		return true;
	}
}
